
//
//  AddFriendViewController.m
//  Light
//
//  Created by MiaoYe on 15/10/23.
//  Copyright © 2015年 骁唐. All rights reserved.
//

#import "AddFriendViewController.h"
#import "UserConfig.h"
#import "AFNetworking.h"
#import "NetworkTool.h"
#import "constantDefinition.h"
#import <AddressBook/AddressBook.h>
#import <AddressBookUI/AddressBookUI.h>
#import "LoginViewController.h"
@interface AddFriendViewController ()<UITextFieldDelegate,MBProgressHUDDelegate,ABPeoplePickerNavigationControllerDelegate,UINavigationControllerDelegate,UIAlertViewDelegate>
@property (weak, nonatomic) IBOutlet UIImageView *backGround;

//系统内置的联系人view对象
@property (nonatomic)ABPeoplePickerNavigationController *picker;

@end


@implementation AddFriendViewController
{
    UIAlertView *alert;
    
}
- (void)viewDidLayoutSubviews{
    [super viewWillLayoutSubviews];
    self.picker.peoplePickerDelegate = self;
    //[self presentViewController:self.picker animated:YES completion:nil];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.phoneTelLabel.delegate = self;
    MBPROGRESS_ALLOC;//MBP初始化。
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
#pragma mark -
#pragma mark 添加好友
- (void)addFriend {
    [_mbProgressHud show:YES];
    
    UserConfig *userConfig = [UserConfig sharingUserConfig];
    
    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
    httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
    
    __weak AddFriendViewController *weakSelf =  self;
    NSDictionary *dic = @{@"Token":[userConfig getToken],@"cellPhone":_phoneTelLabel.text};
    //地址
    [httpManager POST:ADD_FRIEND parameters:dic
              success:^(AFHTTPRequestOperation *operation, id responseObject) {
                  
                  NSDictionary *dic = [NetworkTool toNSDictionary:responseObject];
                  NSLog(@"获取成功");
                  //NSDictionary *resDic = [NetworkTool parseJSONStringToNSDictionary:dic[@"b"]];
                  
                  if ([dic[@"a"] intValue] == 1) {
                      NSLog(@"添加成功");
                      ALERT_VIEW(@"添加成功");
                      [weakSelf.navigationController popViewControllerAnimated:YES];
                      
                  }else if ([dic[@"a"] intValue] == -1) {
                      if (TJJiOS8)
                      {
                      UIAlertController  * Alertview =  [UIAlertController alertControllerWithTitle:@"您的登录过期请,您重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
                      
                      [self presentViewController:Alertview animated:YES completion:nil];
                      
                      UIAlertAction *action = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                          
                          UserConfig *config = [UserConfig sharingUserConfig];
                          [config setHaveLogin:@"lalala"];
                          [config setToken:@"123"];
                          [config setUserHeadData:nil];
                          
                          UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
                          LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
                          loginVc.quit = YES;
                          [self.navigationController pushViewController:loginVc animated:YES];
                      }];
                      
                      [Alertview addAction:action];
                      }
                      else
                      {
                          UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您的登录过期,请您重新登录" delegate:self cancelButtonTitle:@"重新登录" otherButtonTitles:nil, nil];
                          alertView.tag = 97;
                          [alertView show];
                      }
                  }else if ([dic[@"a"] intValue] == 0) {
                      ALERT_VIEW(@"获取失败");
                  }else if ([dic[@"a"] intValue] == -2) {
                      ALERT_VIEW(@"该会员不存在");
                  }
                  _mbProgressHud.hidden = YES;
              }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  ALERT_VIEW(@"信息获取失败");
                  _mbProgressHud.hidden = YES;
              }];
}
#pragma mark -
#pragma mark  通讯录添加好友
- (void)addFriendWith:(NSString *)phone {
    [_mbProgressHud show:YES];
    
    UserConfig *userConfig = [UserConfig sharingUserConfig];
    
    AFHTTPRequestOperationManager *httpManager = [AFHTTPRequestOperationManager manager];
    httpManager.requestSerializer = [[AFHTTPRequestSerializer alloc]init];
    httpManager.responseSerializer = [[AFHTTPResponseSerializer alloc]init];
    
    __weak AddFriendViewController *weakSelf =  self;
    NSDictionary *dic = @{@"Token":[userConfig getToken],@"cellPhone":phone};
    //地址
    [httpManager POST:ADD_FRIEND parameters:dic
              success:^(AFHTTPRequestOperation *operation, id responseObject) {
                  
                  NSDictionary *dic = [NetworkTool toNSDictionary:responseObject];
                  NSLog(@"获取成功");
                  //NSDictionary *resDic = [NetworkTool parseJSONStringToNSDictionary:dic[@"b"]];
                  
                  if ([dic[@"a"] intValue] == 1) {
                      
                      NSLog(@"添加成功");
                      ALERT_VIEW(@"添加成功");
                      [weakSelf.navigationController popViewControllerAnimated:YES];
                      
                  }else if ([dic[@"a"] intValue] == -1) {
                      if (TJJiOS8)
                      {
                          UIAlertController  * Alertview =  [UIAlertController alertControllerWithTitle:@"您的登录过期,请您重新登录" message:nil preferredStyle:UIAlertControllerStyleAlert];
                          
                          [self presentViewController:Alertview animated:YES completion:nil];
                          
                          UIAlertAction *action = [UIAlertAction actionWithTitle:@"重新登录" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
                              
                              UserConfig *config = [UserConfig sharingUserConfig];
                              [config setHaveLogin:@"lalala"];
                              [config setToken:@"123"];
                              [config setUserHeadData:nil];
                              
                              UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
                              LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
                              loginVc.quit = YES;
                              [self.navigationController pushViewController:loginVc animated:YES];
                          }];
                          
                          [Alertview addAction:action];
                      }
                      else
                      {
                          UIAlertView * alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您的登录过期,请您重新登录" delegate:self cancelButtonTitle:@"重新登录" otherButtonTitles:nil, nil];
                          alertView.tag = 97;
                          [alertView show];
                      }
                      
                  }else if ([dic[@"a"] intValue] == 0) {
                      
                      ALERT_VIEW(@"获取失败");
                  }else if ([dic[@"a"] intValue] == -2) {
                      
                      ALERT_VIEW(@"该会员不存在");
                  }
                  _mbProgressHud.hidden = YES;
                  
              }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
                  ALERT_VIEW(@"信息获取失败");
                  _mbProgressHud.hidden = YES;
              }];
}


- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    _placeholderLabel.hidden = YES;
    return YES;
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
    if (textField.text.length == 0) {
        _placeholderLabel.hidden = NO;
    }
    return YES;
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];//隐藏键盘
    
    if ([TJJDefines isMobile:textField.text]) {
        [self addFriend];
    }
    return YES;
}

- (IBAction)bookBtnAction:(id)sender {
    
    ABPeoplePickerNavigationController *peoplePicker = [[ABPeoplePickerNavigationController alloc] init];
    peoplePicker.peoplePickerDelegate = self;
    [self presentViewController:peoplePicker animated:YES completion:nil];
    
    
}

#pragma mark -- ABPeoplePickerNavigationControllerDelegate
- (void)peoplePickerNavigationController:(ABPeoplePickerNavigationController*)peoplePicker didSelectPerson:(ABRecordRef)person property:(ABPropertyID)property identifier:(ABMultiValueIdentifier)identifier {
    
   // ABMultiValueRef valuesRef = ABRecordCopyValue(person, kABPersonPhoneProperty);
    // CFIndex index = ABMultiValueGetIndexForIdentifier(valuesRef,identifier);
    //__unused CFStringRef value = ABMultiValueCopyValueAtIndex(valuesRef,index);
    ABMultiValueRef phone = ABRecordCopyValue(person, kABPersonPhoneProperty);
    for (int k = 0; k<ABMultiValueGetCount(phone); k++)
    {
        //获取电话Label
        // __unused   NSString * personPhoneLabel = (NSString*)CFBridgingRelease(ABAddressBookCopyLocalizedLabel(ABMultiValueCopyLabelAtIndex(phone, k)));
        //获取該Label下的电话值
        NSString * personPhone = (NSString*)CFBridgingRelease(ABMultiValueCopyValueAtIndex(phone, k));
        NSLog(@"%@",personPhone);
        
        [self addFriendWith:[self checkPhoneNum:personPhone]];
        
    }
}
- (BOOL)peoplePickerNavigationController: (ABPeoplePickerNavigationController *)peoplePicker
      shouldContinueAfterSelectingPerson:(ABRecordRef)person
{
    
    return NO;
}


- (void)peoplePickerNavigationControllerDidCancel:(ABPeoplePickerNavigationController *)peoplePicker
{
    [peoplePicker dismissViewControllerAnimated:YES completion:nil];
}

- (IBAction)backBtnAction:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (NSString *)checkPhoneNum:(NSString *)phoneNumber {
    
    NSString *threeStr = [phoneNumber substringWithRange:NSMakeRange(0, 3)];
    NSString *leftStr;
    NSMutableArray *array = [[NSMutableArray alloc]init];
    NSString *resultStr = @"";
    
    if ([NetworkTool isMobileNumber:phoneNumber]) {
        return phoneNumber;
    }else {
        if ([threeStr isEqualToString:@"+86"]) {
            leftStr = [phoneNumber substringWithRange:NSMakeRange(3, phoneNumber.length - 3)];
        }else {
            leftStr = phoneNumber;
        }
        //遍历剩下的字符 放入数组
        for(int i =0; i < [leftStr length]; i++)
        {
            [array addObject:[leftStr substringWithRange:NSMakeRange(i, 1)]];
        }
        //去除空字符串和-
        for (int j = 0; j<array.count; j++) {
            int asciiCode = [array[j] characterAtIndex:0];
            if ( asciiCode < 48 || asciiCode > 57) {
                [array removeObjectAtIndex:j];
            }
        }
        //拼接得到最后的号码
        
        for (int k = 0; k < array.count; k ++) {
            
            resultStr = [NSString stringWithFormat:@"%@%@",resultStr,array[k]];
        }
        
        return resultStr;
        
    }
    
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    //强制竖屏
    [[UIDevice currentDevice] setValue:[NSNumber numberWithInteger:
                                        UIInterfaceOrientationPortrait]  forKey:@"orientation"];
    long long int currentTimeInt = [TJJDefines getTimeIntSince1970Current];
    if (currentTimeInt>=16200&& currentTimeInt <=34200) {
        self.backGround.image = [UIImage imageNamed:@"backgroundOne"];
    }else if (currentTimeInt>34200 && currentTimeInt<=55800)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundTwo"];
    }else if (currentTimeInt>55800 && currentTimeInt<=70200)
    {
        self.backGround.image = [UIImage imageNamed:@"backgroundThree"];
    }else if(currentTimeInt >70200 || currentTimeInt<16200)
    {
        self.backGround.image = [UIImage imageNamed:@"background_night"];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (alertView.tag) {
        case 97:
        {//重新登录
            UserConfig *config = [UserConfig sharingUserConfig];
            [config setHaveLogin:@"lalala"];
            [config setToken:@"123"];
            [config setUserHeadData:nil];
            
            UIStoryboard *LoginSt = [UIStoryboard storyboardWithName:@"Login" bundle:nil];
            LoginViewController *loginVc = [LoginSt instantiateViewControllerWithIdentifier:@"loginViewId"];
            loginVc.quit = YES;
            [self.navigationController pushViewController:loginVc animated:YES];
        }
            break;
        default:
            break;
    }
}

@end
